// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// Author: Markus Gutschke

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "check.h"
#include "control_job_status.h"
#include "http.h"
#include "multipart.h"
#include "stringprintf.h"


void controlJobStatus(const char *url, struct OAuth2 *oauth2,
                      const char *jobid, enum JobStatus status,
                      int code, const char *msg) {
  // Construct "control" URL
  char *api = stringPrintf(NULL, "%s/control", url);

  // Send the control request
  struct MultiPart multipart;
  initMultiPart(&multipart);
  addToMultiPart(&multipart, "jobid", jobid, -1, "text/plain");
  addToMultiPart(&multipart, "status",
                 status == S_QUEUED      ? "QUEUED" :
                 status == S_IN_PROGRESS ? "IN_PROGRESS" :
                 status == S_DONE        ? "DONE" : "ERROR",
                 -1, "text/plain");
  if (status == S_ERROR) {
    char buf[22];
    snprintf(buf, sizeof(buf), "%d", status);
    addToMultiPart(&multipart, "code", buf, -1, "text/plain");
    addToMultiPart(&multipart, "message", msg ? msg : "", -1, "text/plain");
  }
  const char *body = POST(api, oauth2, &multipart, M_MULTIPART);
  free(api);
  destroyMultiPart(&multipart);

  // Parse response
  struct JSON *json = newJSON(body);
  free((void *)body);

  // Verify that the fetch request was successful
  check(json->type == J_OBJECT);
  const struct JSON *success;
  check((success = (const struct JSON *)
         getFromHashMap(&json->obj, "success")) &&
        success->type == J_TRUE);
  
  // This is a "void" function. Discard response.
  deleteJSON(json);
}
